/**
 * 通用网络请求处理
 * @param data
 * @param status
 * @param header
 * @param config
 */
var processRequestError = function (deferred, data, status, header, config) {
  deferred.reject(new Error('网络异常,请重试!'));
};

/**
 * 通过网络请求成功处理
 * @param deferred
 * @param data
 * @param status
 * @param header
 * @param config
 */
var processRequestSucc = function (deferred, data, status, header, config) {
  var result = data;
  if (result.code == 509) {
    deferred.reject(new Error(result.error));
  } else if (result.code == 500) {
    deferred.reject(new Error('网络异常,请重试!'));
  } else if (result.code == 404) {
    deferred.reject(new Error('您没有权限进行该操作,或者访问的资源不存在!'));
  } else if (result.code == 200) {
    deferred.resolve(data);
  }
};


angular.module('app.services', [])

  //.factory('socket', ['AppSettings', 'socketFactory', function (AppSettings, socketFactory) {
  //  //Create socket and connect to http://chat.socket.io
  //  var myIoSocket = io.connect(AppSettings.chatEndpoint);
  //
  //  mySocket = socketFactory({
  //    ioSocket: myIoSocket
  //  });
  //  mySocket.id = Math.random() * (100 - 1)
  //  return mySocket;
  //}])

  /**
   * 应用缓存
   */
  .factory('AppCache', function ($cacheFactory) {
    return $cacheFactory('AppCache');
  })
  /**
   * 本地存储数据
   */
  .factory('Storage', ['$window', function ($window) {
    return {
      //存储单个属性
      set: function (key, value) {
        $window.localStorage[key] = value;
      },
      //读取单个属性
      get: function (key, defaultValue) {
        return $window.localStorage[key] || defaultValue;
      },
      //存储对象，以JSON格式存储
      setObject: function (key, value) {
        $window.localStorage[key] = JSON.stringify(value);
      },
      //读取对象
      getObject: function (key) {
        return JSON.parse($window.localStorage[key] || '{}');
      },
      getUserToken: function () {
        //1. 判断是否已经登录
        var accessToken = this.get('user.accessToken', '');
        var tokenSecret = this.get('user.tokenSecret', '');

        var token = {};
        token.accessToken = accessToken;
        token.tokenSecret = tokenSecret;

        return token;
      },
      clearUserToken: function () {
        this.set('user.accessToken', '')
        this.set('user.tokenSecret', '');
      }

    }
  }])

  .factory('GroupService', ['$q', '$http', 'AppSettings', function ($q, $http, AppSettings) {
    /**
     *  查询我的群
     */
    var getGroupList = function () {
      var deferred = $q.defer();
      var promise = deferred.promise;
      var url = AppSettings.apiEndpoint + 'api/v1/group/list';
      $http.get(url).success(function (data, status, headers, config) {
        processRequestSucc(deferred, data, status, headers, config);
      }).error(function (data, status, header, config) {
        processRequestError(deferred, data, status, header, config);
      });
      return promise;
    }
    /**
     * 查询群的成员列表信息
     * @param groupId
     * @returns {*}
     */
    var getMemberList = function (groupId) {
      var deferred = $q.defer();
      var promise = deferred.promise;
      var url = AppSettings.apiEndpoint + 'api/v1/group/members' + "?groupId=" + groupId;
      $http.get(url).success(function (data, status, headers, config) {
        processRequestSucc(deferred, data, status, headers, config);
      }).error(function (data, status, header, config) {
        processRequestError(deferred, data, status, header, config);
      });
      return promise;
    }
    /**
     * 创建群
     * @param group
     */
    var createGroup = function (group) {
      var deferred = $q.defer();
      var promise = deferred.promise;
      var url = AppSettings.apiEndpoint + 'api/v1/group/create';
      $http.post(url, angular.toJson(group)).success(function (data, status, headers, config) {
        processRequestSucc(deferred, data, status, headers, config);
      }).error(function (data, status, header, config) {
        processRequestError(deferred, data, status, header, config);
      });
      return promise;
    }
    /**
     * 修改群信息
     * @param group
     */
    var modifyGroup = function (group) {
      var deferred = $q.defer();
      var promise = deferred.promise;
      var url = AppSettings.apiEndpoint + 'api/v1/group/update';
      $http.post(url, angular.toJson(group)).success(function (data, status, headers, config) {
        processRequestSucc(deferred, data, status, headers, config);
      }).error(function (data, status, header, config) {
        processRequestError(deferred, data, status, header, config);
      });
      return promise;
    }
    /**
     * 解锁群
     * @param group
     */
    var dissolveGroup = function (group) {
      var deferred = $q.defer();
      var promise = deferred.promise;
      var url = AppSettings.apiEndpoint + 'api/v1/group/dissolve';
      $http.post(url, angular.toJson(group)).success(function (data, status, headers, config) {
        processRequestSucc(deferred, data, status, headers, config);
      }).error(function (data, status, header, config) {
        console.log('+++++++++++++++++++');
        console.log(status);
        console.log(data);
        console.log(header);
        console.log(config);
        processRequestError(deferred, data, status, header, config);
      });
      return promise;
    }

    /**
     * 添加人入群
     * @param userId
     */
    var addGroupMember = function (loginName, groupId) {
      var deferred = $q.defer();
      var promise = deferred.promise;
      var url = AppSettings.apiEndpoint + 'api/v1/group/addMember' + "?groupId=" + groupId + "&loginName=" + loginName;
      $http.post(url, {loginName: loginName}).success(function (data, status, headers, config) {
        processRequestSucc(deferred, data, status, headers, config);
      }).error(function (data, status, header, config) {
        processRequestError(deferred, data, status, header, config);
      });
      return promise;
    }
    /**
     * 移除群成员
     * @param userId
     */
    var removeMember = function (userId, groupId) {
      var deferred = $q.defer();
      var promise = deferred.promise;
      var url = AppSettings.apiEndpoint + 'api/v1/group/removeMember' + "?groupId=" + groupId;
      $http.post(url, {id: userId}).success(function (data, status, headers, config) {
        processRequestSucc(deferred, data, status, headers, config);
      }).error(function (data, status, header, config) {
        processRequestError(deferred, data, status, header, config);
      });
      return promise;
    }
    return {
      getGroupList: getGroupList,
      createGroup: createGroup,
      addGroupMember: addGroupMember,
      removeMember: removeMember,
      dissolveGroup: dissolveGroup,
      modifyGroup: modifyGroup,
      getMemberList: getMemberList,
    };
  }])
  /**
   * 公告
   */
  .factory('NoticeAndMessageService', ['$q', '$http', 'AppSettings', 'Storage',
    function ($q, $http, AppSettings, Storage) {
      var getNoticesAndMessages = function () {
        var deferred = $q.defer();
        var promise = deferred.promise;
        var url = AppSettings.apiEndpoint + 'api/v1/message/list';
        $http.get(url)
          .success(function (data, status, headers, config) {
            processRequestSucc(deferred, data, status, headers, config);
          })
          .error(function (data, status, headers, config) {
            processRequestError(deferred, data, status, headers, config);
          });
        return promise;
      };
      /**
       * 重置公告的阅读状态
       */
      var resetFlagNoticeReadState = function (noticeRecordId) {
        var deferred = $q.defer();
        var promise = deferred.promise;
        var url = AppSettings.apiEndpoint + 'api/v1/message/notice/setHasRead?noticeRecordId=' + noticeRecordId;
        $http.get(url)
          .success(function (data, status, headers, config) {
            processRequestSucc(deferred, data, status, headers, config);
          })
          .error(function (data, status, headers, config) {
            processRequestError(deferred, data, status, headers, config);
          });
        return promise;
      };
      /**
       * 重置个人通知的阅读状态
       */
      var resetFlagPrivateMessageReadState = function (privateNoticeMessageId) {
        var deferred = $q.defer();
        var promise = deferred.promise;
        var url = AppSettings.apiEndpoint + 'api/v1/message/privateMessage/setHasRead?privateNoticeMessageId=' + privateNoticeMessageId;
        $http.get(url)
          .success(function (data, status, headers, config) {
            processRequestSucc(deferred, data, status, headers, config);
          })
          .error(function (data, status, headers, config) {
            processRequestError(deferred, data, status, headers, config);
          });
        return promise;
      };
      return {
        resetFlagPrivateMessageReadState: resetFlagPrivateMessageReadState,
        resetFlagNoticeReadState: resetFlagNoticeReadState,
        getNoticesAndMessages: getNoticesAndMessages,
      }
    }])

  .factory('AuxiliaryPoliceService', ['$q', '$http', 'AppSettings', 'Storage',
    function ($q, $http, AppSettings, Storage) {

      var getRecords = function (searchCondition) {
        var deferred = $q.defer();
        var promise = deferred.promise;
        var url = AppSettings.apiEndpoint;
        var postfix;
        switch (searchCondition.collectionType) {
          case '车辆':
            postfix = '/api/v1/auxiliaryPolice/record/vehicle/list';
            break;
          case '物品':
            postfix = '/api/v1/auxiliaryPolice/record/goods/list';
            break;
          case '事件':
            postfix = '/api/v1/auxiliaryPolice/record/event/list';
            break;
          case '人员':
            postfix = '/api/v1/auxiliaryPolice/record/person/list';
            break;
        }
        var url = url + postfix;
        $http.post(url, angular.toJson(searchCondition)).success(function (data, status, headers, config) {
          processRequestSucc(deferred, data, status, headers, config);
        }).error(function (data, status, headers, config) {
          processRequestError(deferred, data, status, headers, config);
        });
        return promise;
      };

      /**
       * 录入人员数据
       * @param data
       */
      var recordPersonData = function (data) {
        var deferred = $q.defer();
        var promise = deferred.promise;
        var url = AppSettings.apiEndpoint + 'api/v1/auxiliaryPolice/record/person/add';
        $http.post(url, angular.toJson(data)).success(function (data, status, headers, config) {
          processRequestSucc(deferred, data, status, headers, config);
        }).error(function (data, status, header, config) {
          processRequestError(deferred, data, status, headers, config);
        });
        return promise;
      };
      /**
       * 录入物品数据
       * @param data
       */
      var recordGoodsData = function (data) {
        var deferred = $q.defer();
        var promise = deferred.promise;
        var url = AppSettings.apiEndpoint + 'api/v1/auxiliaryPolice/record/goods/add';
        $http.post(url, angular.toJson(data)).success(function (data, status, headers, config) {
          processRequestSucc(deferred, data, status, headers, config);
        }).error(function (data, status, header, config) {
          processRequestError(deferred, data, status, headers, config);
        });
        return promise;
      };

      /**
       * 录入车辆数据
       * @param data
       */
      var recordVehicleData = function (data) {
        var deferred = $q.defer();
        var promise = deferred.promise;
        var url = AppSettings.apiEndpoint + 'api/v1/auxiliaryPolice/record/vehicle/add';

        var data = angular.toJson(data);

        $http.post(url, data).success(function (data, status, headers, config) {
          processRequestSucc(deferred, data, status, headers, config);
        }).error(function (data, status, header, config) {
          processRequestError(deferred, data, status, headers, config);
        });
        return promise;
      };
      /**
       * 录入事件数据
       * @param data
       */
      var recordEventData = function (data) {
        var deferred = $q.defer();
        var promise = deferred.promise;
        var url = AppSettings.apiEndpoint + 'api/v1/auxiliaryPolice/record/event/add';
        $http.post(url, angular.toJson(data)).success(function (data, status, headers, config) {
          processRequestSucc(deferred, data, status, headers, config);
        }).error(function (data, status, header, config) {
          processRequestError(deferred, data, status, headers, config);
        });
        return promise;
      };
      return {
        recordPersonData: recordPersonData,
        recordGoodsData: recordGoodsData,
        recordVehicleData: recordVehicleData,
        recordEventData: recordEventData,
        getRecords: getRecords

      };

    }])


  .factory('UserService', ['$rootScope', 'AppCache', '$timeout', '$q', '$http', 'AppSettings', 'Storage', function ($rootScope, AppCache, $timeout, $q, $http, AppSettings, Storage) {

    return {

      getUserToken: function () {
        //1. 判断是否已经登录
        var accessToken = Storage.get('user.accessToken', '');
        var tokenSecret = Storage.get('user.tokenSecret', '');

        var token = {};
        token.accessToken = accessToken;
        token.tokenSecret = tokenSecret;

        return token;
      },

      /**
       * 是否需要登录
       */
      isNeedLogin: function () {
        //2. 已经登录,并且用户在上次登录时选择的"自动登录"
        //if (Storage.get("autoLogin", false)) {
        //  return false;
        //}

        //1. 判断是否已经登录
        var accessToken = Storage.get('user.accessToken', '');
        var tokenSecret = Storage.get('user.tokenSecret', '');


        if ('' != accessToken && '' != tokenSecret) {
          return false;
        }


        //默认需要登录
        return true;
      },
      /**
       * 退出登陆时,需要做数据清理
       */
      doLogout: function () {
        Storage.set("user.accessToken", '');
        Storage.set("user.tokenSecret", '');
      },

      /**
       * 密码修改
       * @param user
       */
      doModifyPwd: function (user) {
        var deferred = $q.defer();
        var promise = deferred.promise;

        //保存下次是否自动登陆到storage中
        var autoLogin = user.autoLogin;
        Storage.set("autoLogin", autoLogin);

        var url = AppSettings.apiEndpoint + 'api/v1/user/modifyPwd';

        $http.post(url, angular.toJson(user))
          .success(function (data, status, headers, config) {
            var accessToken = data.accessToken;
            var tokenSecret = data.tokenSecret;

            Storage.set("user.accessToken", accessToken);
            Storage.set("user.tokenSecret", tokenSecret);

            processRequestSucc(deferred, data, status, headers, config);
          })
          .error(function (data, status, header, config) {
            processRequestError(deferred, data, status, header, config);
          });


        return promise;
      },
      /**
       * 处理登陆业务
       * @param user 用户信息
       * @param callback 登陆处理对调函数
       */
      doLogin: function (user) {

        var deferred = $q.defer();
        var promise = deferred.promise;

        //保存下次是否自动登陆到storage中
        var autoLogin = user.autoLogin;
        Storage.set("autoLogin", autoLogin);

        var url = AppSettings.apiEndpoint + 'api/v1/user/login';


        $http.post(url, angular.toJson(user))
          .success(function (data, status, headers, config) {
            var result = data;
            if (result.code == 509) {
              deferred.reject(new Error(result.error));
            } else if (result.code == 500) {
              deferred.reject(new Error('网络异常,请重试!'));
            } else if (result.code == 200) {
              var accessToken = result.accessToken;
              var tokenSecret = result.tokenSecret;

              Storage.set("user.accessToken", accessToken);
              Storage.set("user.tokenSecret", tokenSecret);


              $rootScope.hotelStatus = data.hotelStatus;
              $rootScope.aduitSuggestion = data.aduitSuggestion;
              $rootScope.unReadMessageCount = data.unReadMessageCount;
              $rootScope.unReadChatMessageCount = data.unReadChatMessageCount;
              $rootScope.userType = data.userType;
              //AppCache.put('mobileMenuUserTypeList', data.mobileMenuUserTypeList);
              $rootScope.mobileMenuUserTypeList = data.mobileMenuUserTypeList;

              deferred.resolve(data);
            }
          })
          .error(function (data, status, header, config) {
            deferred.reject(new Error('网络异常,请重试!'));
          });


        return promise;
      },

      /**
       * 注册
       * @param user
       * @returns {*}
       */
      doRegister: function (user) {
        var deferred = $q.defer();
        var promise = deferred.promise;
        var url = AppSettings.apiEndpoint + 'api/v1/user/register';

        //旅馆注册
        if (user.userType == '4') {
          url = AppSettings.apiEndpoint + 'api/v1/user/registerHotel';
        }
        $http.post(url, angular.toJson(user))
          .success(function (data, status, headers, config) {
            var result = data;
            if (result.code == 509) {
              deferred.reject(new Error(result.error));
            } else if (result.code == 500) {
              deferred.reject(new Error('网络异常,请重试!'));
            } else if (result.code == 200) {
              deferred.resolve(data);
            }
          })
          .error(function (data, status, header, config) {
            deferred.reject(new Error('网络异常,请重试!'));
          });
        return promise;
      },

    }
  }])

  /**
   * 旅馆行业Service
   */
  .service('HotelService', ['$http', '$q', 'AppSettings', function ($http, $q, AppSettings) {
    return {

      /**
       * 用户被拒绝后重新提交旅馆注册资料
       * @param hotel
       */
      doResubmitHotelRegister: function (hotel) {
        var deferred = $q.defer();
        var promise = deferred.promise;
        var url = AppSettings.apiEndpoint + 'api/v1/hotel/resubmitHotelInfo';

        $http.post(url, angular.toJson(hotel))
          .success(function (data, status, headers, config) {
            processRequestSucc(deferred, data, status, headers, config);
          })
          .error(function (data, status, header, config) {
            processRequestError(deferred, data, status, header, config);
          });

        return promise;
      },

      /**
       * 获取旅馆的基本信息
       * @returns {*}
       */
      getHotelBasicInfo: function () {
        var deferred = $q.defer();
        var promise = deferred.promise;
        var url = AppSettings.apiEndpoint + 'api/v1/hotel/basicInfo';
        $http.get(url)
          .success(function (data, status, headers, config) {
            processRequestSucc(deferred, data, status, headers, config);
          })
          .error(function (data, status, headers, config) {
            processRequestError(deferred, data, status, headers, config);
          });
        return promise;
      },

      /**
       * 添加入住人员
       * @param guest 入住人员
       * @param callback
       */
      addGuest: function (guest) {
        var deferred = $q.defer();
        var promise = deferred.promise;
        var url = AppSettings.apiEndpoint + 'api/v1/hotel/add';
        $http.post(url, angular.toJson(guest))
          .success(function (data, status, headers, config) {
            var result = data;
            if (result.code == 509) {
              deferred.reject(new Error(result.error));
            } else if (result.code == 500) {
              deferred.reject(new Error('网络异常,请重试!'));
            } else if (result.code == 200) {
              deferred.resolve(data);
            }
          })
          .error(function (data, status, header, config) {
            deferred.reject(new Error('网络异常,请重试!'));
          });
        return promise;
      },
      modifyHotelSeatCount: function (seatCount) {
        var deferred = $q.defer();
        var promise = deferred.promise;
        var url = AppSettings.apiEndpoint + 'api/v1/hotel/modifySeatCount?hotelseatcount=' + seatCount;
        $http.get(url)
          .success(function (data, status, headers, config) {
            processRequestSucc(deferred, data, status, headers, config);
          })
          .error(function (data, status, header, config) {
            processRequestError(deferred, data, status, header, config);
          });
        return promise;
      },

      /**
       * 修改法人信息
       * @param modifyLegalPerson
       * @returns {*}
       */
      modifyLegalPerson: function (newTelephoneNum, nowAddress) {
        var deferred = $q.defer();
        var promise = deferred.promise;
        var url = AppSettings.apiEndpoint + 'api/v1/hotel/modifyLegalPerson?newTelephoneNum=' + newTelephoneNum +"&nowAddress=" +nowAddress;
        $http.get(url)
          .success(function (data, status, headers, config) {
            processRequestSucc(deferred, data, status, headers, config);
          })
          .error(function (data, status, header, config) {
            processRequestError(deferred, data, status, header, config);
          });
        return promise;
      },
      /**
       * 添加从业人员
       * @param hotelWorker 从业人员
       * @param callback
       */
      addWork: function (data) {
        var deferred = $q.defer();
        var promise = deferred.promise;
        var url = AppSettings.apiEndpoint + 'api/v1/hotel/addWorker';
        $http.post(url, angular.toJson(data))
          .success(function (data, status, headers, config) {
            processRequestSucc(deferred, data, status, headers, config);
          })
          .error(function (data, status, header, config) {
            processRequestError(deferred, data, status, header, config);
          });
        return promise;
      },
      /**
       * 根据点击查询旅馆的入住情况
       * @param callback
       */
      getGuests: function (callback) {

      },
      /**
       * 查询旅馆从业人员列表
       * @returns {*}
       */
      getWorkerList: function () {
        var deferred = $q.defer();
        var promise = deferred.promise;
        var url = AppSettings.apiEndpoint + 'api/v1/hotel/workerList';
        $http.get(url)
          .success(function (data, status, headers, config) {
            processRequestSucc(deferred, data, status, headers, config);
          })
          .error(function (data, status, header, config) {
            processRequestError(deferred, data, status, header, config);
          });
        return promise;
      },
      /**
       * 查询旅馆从业人员列表
       * @returns {*}
       */
      getGuestList: function (guest) {
        var deferred = $q.defer();
        var promise = deferred.promise;
        var url = AppSettings.apiEndpoint + 'api/v1/hotel/guestList';
        $http.post(url, angular.toJson(guest))
          .success(function (data, status, headers, config) {
            processRequestSucc(deferred, data, status, headers, config);
          })
          .error(function (data, status, header, config) {
            processRequestError(deferred, data, status, header, config);
          });
        return promise;
      },
      removeWorker: function (worker) {
        var deferred = $q.defer();
        var promise = deferred.promise;
        var url = AppSettings.apiEndpoint + 'api/v1/hotel/removeWorker';
        $http.post(url, angular.toJson(worker))
          .success(function (data, status, headers, config) {
            processRequestSucc(deferred, data, status, headers, config);
          })
          .error(function (data, status, header, config) {
            processRequestError(deferred, data, status, header, config);
          });
        return promise;
      }
    }
  }])


  .factory('FeedbackService', ['$http', '$q', 'AppSettings', function ($http, $q, AppSettings) {
    var sendFeedback = function (feedback) {
      var deferred = $q.defer();
      var promise = deferred.promise;
      var url = AppSettings.apiEndpoint + 'api/v1/feedback/add';
      $http.post(url, angular.toJson(feedback))
        .success(function (data, status, headers, config) {
          if (data.code == 200) {
            deferred.resolve(data);
          } else {
            deferred.reject(new Error('服务器异常,请重试!'));
          }
        })
        .error(function (data, status, header, config) {
          deferred.reject(new Error('网络异常,请重试!'));
        });
      return promise;
    };
    /**
     * 获取举报的历史记录(最新的30条)
     * @param worker
     * @returns {*}
     */
    var getHistoryList = function () {
      var deferred = $q.defer();
      var promise = deferred.promise;
      var url = AppSettings.apiEndpoint + 'api/v1/feedback/list';
      $http.get(url)
        .success(function (data, status, headers, config) {
          processRequestSucc(deferred, data, status, headers, config);
        })
        .error(function (data, status, header, config) {
          processRequestError(deferred, data, status, header, config);
        });
      return promise;
    }


    return {sendFeedback: sendFeedback, getHistoryList: getHistoryList};

  }])

  .factory('CommonService',
    ['$http', '$ionicActionSheet', '$rootScope', '$timeout', 'Storage', '$cordovaCamera', '$q', 'AppSettings',
      '$cordovaDatePicker', '$filter', '$cordovaGeolocation', 'AppCache', 'Storage',
      function ($http, $ionicActionSheet, $rootScope, $timeout, Storage, $cordovaCamera,
                $q, AppSettings, $cordovaDatePicker, $filter, $cordovaGeolocation, AppCache, Storage) {

        /**
         * 获取地址位置信息
         */
        var getLocation = function () {
          var deferred = $q.defer();
          var promise = deferred.promise;

          var isAndroid = ionic.Platform.isAndroid();
          //android平台使用百度地图进行定位
          if (isAndroid) {
            // 进行定位
            baidu_location.getCurrentPosition(function (data) {
              // alert(data);
              //latitude : 纬度,
              //  lontitude: 经度,
              var latitude = data.latitude;
              var lontitude = data.lontitude;

              var data = latitude + ',' + lontitude;
              deferred.resolve(data);

              console.log(data);
            }, function (error) {
              console.log("定位失败");
              console.log(error);
              deferred.reject(new Error('获取地理位置信息失败,请确认已经开启定位权限!'));
              alert(error.message);
            });

          }

          //其他平台使用cordovaGeolocation进行定位
          else {
            var posOptions = {timeout: 10000, enableHighAccuracy: true};
            $cordovaGeolocation.getCurrentPosition(posOptions).then(function (position) {
              var lat = position.coords.latitude
              var long = position.coords.longitude

              var data = lat + ',' + long;

              console.log('定位:' + data);

              deferred.resolve(data);

            }, function (err) {
              deferred.reject(new Error('获取地理位置信息失败,请确认已经开启定位权限!'));
              alert(err.message);
            });
          }


          return promise;
        };

        return {
          /**
           * 获取地址位置信息
           */
          getLocation: getLocation,

          /**
           * 从服务器上获取初始化数据
           * @param cb 处理完成回调函数
           */
          getInitData: function () {
            var deferred = $q.defer();
            var promise = deferred.promise;
            var url = AppSettings.apiEndpoint + 'api/v1/base/initData';
            $http.get(url)
              .success(function (data, status, headers, config) {
                if (data.code == 200) {
                  $rootScope.userTypes = data.userTypeList;
                  $rootScope.officeList = data.officeList;
                  $rootScope.vehicleColorList = data.vehicleColorList;
                  $rootScope.vehicleCategoryList = data.vehicleCategoryList;
                  $rootScope.eventSourceDictList = data.eventSourceDictList;
                  $rootScope.hotelStatus = data.hotelStatus;
                  $rootScope.aduitSuggestion = data.aduitSuggestion;
                  $rootScope.unReadMessageCount = data.unReadMessageCount;
                  $rootScope.unReadChatMessageCount = data.unReadChatMessageCount;
                  $rootScope.userType = data.userType;

                  //如果服务器端要求登陆,则清理掉本地缓存的accessToken,tokenSecret
                  if (data.isNeedLogin) {
                    Storage.clearUserToken();
                  }
                  ;


                  $rootScope.user = {};

                  if (data.name) {
                    Storage.set("userName", data.name);
                    console.log("data.name:" + data.name);
                  }
                  //$rootScope.mobileMenuUserTypeList = data.mobileMenuUserTypeList;

                  // AppCache.put('mobileMenuUserTypeList', data.mobileMenuUserTypeList);
                  //  console.log(AppCache.get('mobileMenuUserTypeList'));
                  $rootScope.mobileMenuUserTypeList = data.mobileMenuUserTypeList;
                  deferred.resolve(data);
                } else {
                  deferred.reject(new Error('服务器异常,请重试!'));
                }
              })
              .error(function (data, status, header, config) {
                deferred.reject(new Error('网络异常,请重试!'));
              });
            return promise;
          }
          ,
          getPhoto: function (options) {
            var deferred = $q.defer();
            var promise = deferred.promise;


            $ionicActionSheet.show({
              buttons: [
                {text: '相册'},
                {text: '拍照'}
              ],
              // destructiveText: 'Delete',
              // titleText: 'Modify your album',
              cancelText: '取消',
              cancel: function () {
                // add cancel code..
              },
              buttonClicked: function (index) {

                options = options || {
                    quality: 60,
                    destinationType: Camera.DestinationType.DATA_URL,
                    sourceType: Camera.PictureSourceType.CAMERA,
                    allowEdit: true,
                    encodingType: Camera.EncodingType.JPEG,
                    popoverOptions: CameraPopoverOptions,
                    saveToPhotoAlbum: false,
                    correctOrientation: true
                    ,
                    targetWidth: 800,
                    targetHeight: 600,

                  };

                if (index == 0) {
                  options.sourceType = Camera.PictureSourceType.PHOTOLIBRARY;
                  getPictureFromCameraBySourceType(options);
                } else {
                  options.sourceType = Camera.PictureSourceType.CAMERA;
                  getPictureFromCameraBySourceType(options);
                }
                return true;
              }

            });

            /**
             * 通过相机获取图片
             */
            var getPictureFromCameraBySourceType = function (options) {

              console.log(angular.toJson(options));

              $cordovaCamera.getPicture(options).then(function (imageData) {
                deferred.resolve("data:image/jpeg;base64," + imageData);
              }, function (err) {
                deferred.reject(err);
              });
            };


            return promise;
          }
          ,
          getTimePicker: function (options) {

            var deferred = $q.defer();
            var promise = deferred.promise;


            options = options || {
                date: new Date(),
                mode: 'date', // or 'time'
                maxDate: new Date() + 1000*60*60*24,
                allowOldDates: true,
                allowFutureDates: false,
                doneButtonLabel: '确定',
                //doneButtonColor: '#F2F3F4',
                cancelButtonLabel: '取消',
                locale:'zh_CN'
                //cancelButtonColor: '#000000'
              };
            document.addEventListener("deviceready", function () {

              $cordovaDatePicker.show(options).then(function (date) {
                var timeString = $filter('date')(date, "yyyy-MM-dd");
                deferred.resolve(timeString, date);
              });

            }, false);

            return promise;

          }


        };
      }])


  .factory('localStorageService', [function () {
    return {
      get: function localStorageServiceGet(key, defaultValue) {
        var stored = localStorage.getItem(key);
        try {
          stored = angular.fromJson(stored);
        } catch (error) {
          stored = null;
        }
        if (defaultValue && stored === null) {
          stored = defaultValue;
        }
        return stored;
      },
      update: function localStorageServiceUpdate(key, value) {
        if (value) {
          localStorage.setItem(key, angular.toJson(value));
        }
      },
      clear: function localStorageServiceClear(key) {
        localStorage.removeItem(key);
      }
    };
  }])

  .factory('dateService', [function () {
    return {
      handleMessageDate: function (messages) {
        var i = 0,
          length = 0,
          messageDate = {},
          nowDate = {},
          weekArray = ["周日", "周一", "周二", "周三", "周四", "周五", "周六"],
          diffWeekValue = 0;
        if (messages) {
          nowDate = this.getNowDate();
          length = messages.length;
          for (i = 0; i < length; i++) {
            messageDate = this.getMessageDate(messages[i]);
            if (!messageDate) {
              return null;
            }
            if (nowDate.year - messageDate.year > 0) {
              messages[i].lastMessage.time = messageDate.year + "";
              continue;
            }
            if (nowDate.month - messageDate.month >= 0 ||
              nowDate.day - messageDate.day > nowDate.week) {
              messages[i].lastMessage.time = messageDate.month +
                "月" + messageDate.day + "日";
              continue;
            }
            if (nowDate.day - messageDate.day <= nowDate.week &&
              nowDate.day - messageDate.day > 1) {
              diffWeekValue = nowDate.week - (nowDate.day - messageDate.day);
              messages[i].lastMessage.time = weekArray[diffWeekValue];
              continue;
            }
            if (nowDate.day - messageDate.day === 1) {
              messages[i].lastMessage.time = "昨天";
              continue;
            }
            if (nowDate.day - messageDate.day === 0) {
              messages[i].lastMessage.time = messageDate.hour + ":" + messageDate.minute;
              continue;
            }
          }
          // console.log(messages);
          // return messages;
        } else {
          console.log("messages is null");
          return null;
        }

      },
      getNowDate: function () {
        var nowDate = {};
        var date = new Date();
        nowDate.year = date.getFullYear();
        nowDate.month = date.getMonth();
        nowDate.day = date.getDate();
        nowDate.week = date.getDay();
        nowDate.hour = date.getHours();
        nowDate.minute = date.getMinutes();
        nowDate.second = date.getSeconds();
        return nowDate;
      },
      getMessageDate: function (message) {
        var messageDate = {};
        var messageTime = "";
        //2015-10-12 15:34:55
        var reg = /(^\d{4})-(\d{1,2})-(\d{1,2})\s(\d{1,2}):(\d{1,2}):(\d{1,2})/g;
        var result = new Array();
        if (message) {
          messageTime = message.lastMessage.originalTime;
          result = reg.exec(messageTime);
          if (!result) {
            console.log("result is null");
            return null;
          }
          messageDate.year = parseInt(result[1]);
          messageDate.month = parseInt(result[2]);
          messageDate.day = parseInt(result[3]);
          messageDate.hour = parseInt(result[4]);
          messageDate.minute = parseInt(result[5]);
          messageDate.second = parseInt(result[6]);
          // console.log(messageDate);
          return messageDate;
        } else {
          console.log("message is null");
          return null;
        }
      }
    };
  }])


;

